package mrusanov.sounds

import xml.{NodeSeq, XML}
import java.io.File

object SpriteSoundConfigurationLoader {
  val EMPTY = new SpriteSoundConfiguration(None, None, None, None, 0)

  lazy val configurations = loadConfigurations

  private def loadConfigurations:Map[String, SpriteSoundConfiguration] = {
    val path = getClass.getResource("/conf/spriteSoundConfiguration.xml").toURI
    val xml = XML.loadFile(new File(path))

    val res = for (node <- xml \ "spriteConfiguration") yield {
      val name = (node \ "@name").toString()
      val attackSuccess = someOrNone(node \ "@attackSuccess")
      val attackFail = someOrNone(node \ "@attackFail")
      val death = someOrNone(node \ "@death")
      val hit = someOrNone(node \ "@hit")
      val attackCorrection = someOrNone(node \ "@attackCorrection").map(_.toInt) .getOrElse(0)

      val config = new SpriteSoundConfiguration(sound(attackSuccess), sound(attackFail), sound(death), sound(hit),
        attackCorrection)
      (name, config)
    }

    res.toMap
  }

  private def someOrNone(seq:NodeSeq):Option[String] = {
    if (seq.isEmpty) None
    else Some(seq.toString())
  }

  private def sound(name:Option[String]) = name.map(SoundConfigLoader.soundsMap(_))
}
